#include "../include/UserRegisterSection.h"
#include "../include/MySQLClient.hpp"
#include "../include/userMananger.hpp"

#include <stdlib.h>


//为了模拟效果用户名暂时采取全局变量
//string user_register;


namespace rocket
{

string UserRegisterSection1::GenRandomString(int length)
{
    
    int flag, i;  
    char* string;  
    srand((unsigned) time(NULL ));  
    if ((string = (char*) malloc(length)) == NULL )  {  
        printf("malloc failed!flag:14\n");  
        return NULL ;  
    }  
    for (i = 0; i < length+1; i++)  {  
        flag = rand() % 3;  
        switch (flag)  {  
            case 0:  string[i] = 'A' + rand() % 26;  break;  
            case 1:  string[i] = 'a' + rand() % 26;  break;  
            case 2:  string[i] = '0' + rand() % 10;  break;  
            default:  string[i] = 'x';  break;  
        }
    }
    string[length] = '\0';
    return string;  

}

string UserRegisterSection1::CreateMD5Salt()
{
    return "$1$"+GenRandomString(8);
}
void UserRegisterSection1::process()
{
 
    //用户名从客户端发送到服务端
    string user_register=_packet._msg;

    vector<vector<string>>result=rlt::MySQLClient::getInstance()->read_operation(string("SELECT * FROM `account` WHERE user_name like '")+user_register+"';");

    //判断用户名是否已存在
    if(result.size()==0)
    {
        cout<<"user not exist"<<endl;
        //产生随机盐值
        string salt=CreateMD5Salt();
        
        cout<<"salt="<<salt<<endl;

        //将用户名和盐值写入mysql
        rlt::MySQLClient::getInstance()->write_operation(string("insert into `account` (user_name,user_salt) values('")+user_register+"','"+salt+"');");
        
        user client(user_register,salt,_conn,USER_IS_REGISTERING);
        //将用户信息存入userMananger中
        userMananger::get_instance()->add_user(_conn->getfd(), client);
        //将盐值发送给客户端
        _conn->sendInLoop(wd::TLV(TASK_TYPE_REGISTER_SECTION1_RESP_OK,salt.size(),salt.c_str()));
        
    }
    else
    {
        _conn->sendInLoop(wd::TLV(TASK_TYPE_REGISTER_SECTION1_RESP_ERROR,0,""));
    }
    

}

void UserRegisterSection2::process() 
{
    user *client=userMananger::get_instance()->get_user(_conn->getfd());
    string user_register=client->_name;
    //获取到客户端发来的密文
    string encrypted=_packet._msg;
    
    cout<<"encrypted="<<encrypted<<endl;
    //34是密文的长度
    if(encrypted.size()==34)
    {
        //将密文写入到对应的用户的数据库中
        rlt::MySQLClient::getInstance()->write_operation(string("UPDATE `account` SET user_encrypted = '")+encrypted+"' WHERE user_name = '"+user_register+"';");
//        //修改用户状态为已注册并添加密文信息
//        client->_status=USER_HAS_REGISTER;
//        client->_encrypted=encrypted;
        //注册完成，删除用户
        userMananger::get_instance()->delete_user(_conn->getfd());
        //服务端给客户端发送注册结果  
        _conn->sendInLoop(wd::TLV(TASK_TYPE_REGISTER_SECTION2_RESP_OK,0,"")) ;

    }
    else
    {
        _conn->sendInLoop(wd::TLV(TASK_TYPE_REGISTER_SECTION2_RESP_ERROR,0,"")) ;
    }


}

}//end of namespace wd
